package com.pys.filter;

import java.io.IOException;

import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pys.beans.UserSessionBean;
import com.pys.enums.Statu;

public class LoginFilter implements Filter {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(LoginFilter.class);

	public static final String LOGIN_PAGE = "/login.jsf";
	public static final String KULLANICI_BILGI_GUNCELLE_PAGE = "/kullanici_guncelle.jsf";

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		// try {
		// HttpServletRequest req = (HttpServletRequest) servletRequest;
		// HttpServletResponse res = (HttpServletResponse) servletResponse;
		// HttpSession ses = req.getSession(false);
		// String reqURI = req.getRequestURI();
		// if (reqURI.indexOf("/login.xhtml") >= 0
		// || (ses != null
		// && ses.getAttribute("userSessionBean") != null && ((UserSessionBean)
		// ses
		// .getAttribute("userSessionBean")).isLoggedIn())
		// || reqURI.indexOf("/public/") >= 0
		// || reqURI.contains("javax.faces.resource"))
		// filterChain.doFilter(servletRequest, servletResponse);
		// else
		// res.sendRedirect(req.getContextPath() + "/login.xhtml");
		//
		// } catch (Throwable t) {
		// System.out.println(t.getMessage());
		// }

		// -------------------------------------

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession(false);

		UserSessionBean auth = (UserSessionBean) ((session != null) ? session
				.getAttribute("userSessionBean") : null);
		String loginURL = request.getContextPath() + LOGIN_PAGE;
		String kullaniciGuncelleURL = request.getContextPath()
				+ KULLANICI_BILGI_GUNCELLE_PAGE;

		boolean loggedIn = auth != null && auth.isLoggedIn();
		boolean firstLogin = auth != null
				&& auth.getCurrentUser() != null
				&& Statu.FIRST_LOGIN.toString().equals(
						auth.getCurrentUser().getStatu());
		boolean loginRequest = request.getRequestURI().equals(loginURL);
		boolean kullaniciGuncelleRequest = request.getRequestURI().equals(
				kullaniciGuncelleURL);
		boolean resourceRequest = request.getRequestURI().startsWith(
				request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER);

		boolean css = request.getRequestURI().contains("css");
		boolean images = request.getRequestURI().contains("images");
		boolean resources = request.getRequestURI().contains("resources");

		if ((!firstLogin || kullaniciGuncelleRequest || resourceRequest
				|| resources || images)
				&& (loggedIn || loginRequest || resourceRequest || resources || images)) {
			if (!resourceRequest) {
				response.setHeader("Cache-Control",
						"no-cache, no-store, must-revalidate"); // HTTP 1.1.
				response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
				response.setDateHeader("Expires", 0); // Proxies.
			}

			filterChain.doFilter(request, response);
			return;
		} else if (firstLogin && !kullaniciGuncelleRequest) {
			System.out.println("firstLogin" + firstLogin + "-"
					+ kullaniciGuncelleRequest + "-" + kullaniciGuncelleURL
					+ "-" + request.getRequestURI());
			response.sendRedirect(kullaniciGuncelleURL);
		} else {
			System.out.println("login");
			// response.sendRedirect(loginURL);
			filterChain.doFilter(request, response);
		}

		// -------------------------------------------

		// HttpServletRequest httpServletRequest = (HttpServletRequest)
		// servletRequest;
		// HttpServletResponse httpServletResponse = (HttpServletResponse)
		// servletResponse;
		//
		// if (httpServletRequest != null
		// && httpServletRequest.getRequestURI() != null
		// && !httpServletRequest.getRequestURI().toString()
		// .contains(LOGIN_PAGE)) {
		// // managed bean name is exactly the session attribute name
		// UserSessionBean userSessionBean = (UserSessionBean)
		// httpServletRequest
		// .getSession().getAttribute("userSessionBean");
		//
		// if (userSessionBean != null) {
		// if (userSessionBean.isLoggedIn()) {
		// LOGGER.debug("user is logged in");
		// // user is logged in, continue request
		// filterChain.doFilter(servletRequest, servletResponse);
		// } else {
		// LOGGER.debug("user is not logged in");
		// // user is not logged in, redirect to login page
		// httpServletResponse.sendRedirect(httpServletRequest
		// .getContextPath() + LOGIN_PAGE);
		// }
		// } else {
		// LOGGER.debug("userManager not found");
		// // user is not logged in, redirect to login page
		// httpServletResponse.sendRedirect(httpServletRequest
		// .getContextPath() + LOGIN_PAGE);
		// }
		// } else {
		// filterChain.doFilter(servletRequest, servletResponse);
		// }
	}

	public void init(FilterConfig arg0) throws ServletException {
		LOGGER.debug("LoginFilter initialized");
	}

	public void destroy() {
		// close resources
	}

}